package demo.impl.icmp;

import java.util.concurrent.atomic.AtomicInteger;

import org.pcap4j.packet.IcmpV4CommonPacket;
import org.pcap4j.packet.namednumber.IcmpV4Type;
import org.pcap4j.packet.namednumber.IpNumber;

import demo.api.IPv4Service;
import demo.api.IcmpEchoSession;
import demo.api.IcmpService;
import demo.impl.AbstractProtocolService;

/**
 * Icmp服务
 * 
 * @author caohj
 * @date 2017年8月6日
 */
public class IcmpServiceImpl extends AbstractProtocolService<IcmpV4CommonPacket> implements IcmpService {

	private AtomicInteger identifier = new AtomicInteger((int) System.currentTimeMillis());

	public IcmpServiceImpl(IPv4Service ipv4) {
		super(ipv4);

		// 注册子协议
		installHighLevelProtocal(IcmpV4Type.ECHO_REPLY.value(), new IcmpEchoListener());
	}

	@Override
	protected Number getProtocolType() {
		return IpNumber.ICMPV4.value();
	}

	@Override
	public IcmpEchoSession createEchoSession() {
		short identifier = (short) this.identifier.incrementAndGet();
		IcmpEchoListener echoListener = (IcmpEchoListener) getHighLevelProtocal(IcmpV4Type.ECHO_REPLY.value());
		IcmpEchoSessionImpl session = new IcmpEchoSessionImpl((short) identifier, echoListener, this);
		return session;
	}

	@Override
	protected Number getHighLevelProtocolType(IcmpV4CommonPacket packet) {
		return packet.get(IcmpV4CommonPacket.class).getHeader().getType().value();
	}

}
